package com.rskj.cashbook.controller;

import com.rskj.cashbook.response.ResponseEntity;
import com.rskj.cashbook.service.iml.UserInfoService;
import com.rskj.cashbook.util.JwtUtil;
import com.rskj.cashbook.vo.UserInfo;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Optional;

@RestController
@RequestMapping("user")
@AllArgsConstructor
public class LoginController {

    private final UserInfoService userInfoService;

    private final JwtUtil jwtUtil;


    @PostMapping("login")
    public ResponseEntity<String> login(@RequestBody UserInfo userInfo, HttpServletRequest request) {
        UserInfo loginUser = Optional.ofNullable(userInfoService.getUserInfo(userInfo))
                .orElse((UserInfo) new UserInfo().setId("-1"));
        loginUser.setUserName(loginUser.getAccount());
        String token = jwtUtil.generateToken(loginUser, new HashMap<>(), request);
        return ResponseEntity.ok(token);
    }

    @PostMapping("register")
    public ResponseEntity<UserInfo> register(@RequestBody UserInfo userInfo) {
        return ResponseEntity.ok(userInfoService.addUserInfo(userInfo));
    }


    @PostMapping("logout")
    public ResponseEntity<Object> logout(HttpServletRequest request, HttpServletResponse response) {
        return userInfoService.logout(request, response);
    }

    @PostMapping("/up/passwd")
    public ResponseEntity<Object> updatePassword(@RequestBody UserInfo userInfo) {
        return ResponseEntity.ok(userInfoService.updatePassword(userInfo));
    }


}
